package kr.co.sdworld.api.apns.service;

import java.util.List;

import kr.co.sdworld.api.apns.model.ApnsLogin;
import kr.co.sdworld.api.apns.model.ApnsToken;
import kr.co.sdworld.api.apns.model.ApnsTokenSample;
import kr.co.sdworld.api.apns.repository.login.ApnsLoginDao;
import kr.co.sdworld.api.apns.repository.token.ApnsTokenDao;
import kr.co.sdworld.api.apns.repository.tokensample.ApnsTokenSampleDao;
import kr.co.sdworld.common.util.generator.IDGenerator;
import kr.co.sdworld.stone.SpringBeanUtil;
import kr.co.sdworld.webs.ServiceContext;

import org.springframework.stereotype.Service;

@Service
public class TokenServiceImpl implements TokenService 
{
	@Override
	public List<ApnsTokenSample> getTokenSampleList() 
	{
		return null;
	}
	
	@Override
	public List<ApnsTokenSample> getTokenSampleListByAppId(String appId) {
		
		ApnsLogin login = (ApnsLogin)ServiceContext.getSession().getAttribute("login");
		return SpringBeanUtil.repository( ApnsTokenSampleDao.class).search(appId, login.getUserId());
	}
	
	@Override
	public int saveToken(String appId, String deviceToken, String userId, String userPw) 
	{
		ApnsLogin login = SpringBeanUtil.repository( ApnsLoginDao.class).getLoginInfo(userId);
		int result = 0;
		if(login != null && login.getUserPw().equals(userPw))
		{
			ApnsToken token = new ApnsToken();
			token.setAppId(appId);
			token.setDeviceToken(deviceToken);
			token.setObjId(IDGenerator.generate());
			result = SpringBeanUtil.repository( ApnsTokenDao.class).create(token);
		}
		else {
			throw new RuntimeException("Auth error!");
		}
		return result;
	}
	
	@Override
	public int saveTokenSample(String appId, String deviceToken, String userId,
			String userPw) {
		return saveTokenSample(appId, deviceToken, null, userId, userPw);
	}
	
	@Override
	public int saveTokenSample(String appId, String deviceToken,
			String deviceTokenAlias, String userId, String userPw) {
		ApnsLogin login = SpringBeanUtil.repository( ApnsLoginDao.class).getLoginInfo(userId);
		int result = 0;
		if(login != null && login.getUserPw().equals(userPw))
		{
			ApnsTokenSample token = new ApnsTokenSample();
			token.setAppId(appId);
			token.setUserId(userId);
			token.setDeviceToken(deviceToken);
			token.setDeviceTokenAlias( deviceTokenAlias);
			token.setObjId(IDGenerator.generate());
			result = SpringBeanUtil.repository( ApnsTokenSampleDao.class).create(token);
		}
		else {
			throw new RuntimeException("Auth error!");
		}
		return result;
	}
}
